package com.xdl.flytest.controller;

import com.xdl.flytest.bean.Task;
import com.xdl.flytest.service.TaskService;
import com.xdl.flytest.util.JsonResponseMessage;
import com.xdl.flytest.util.ResponseMsg;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * @Auther: 80736
 * @Date: 2019/1/28 18:37
 * @Description:
 */

@Controller
@RequestMapping("/test")
public class TaskController {

    @Autowired
    private TaskService taskService;

    @GetMapping("/tasks")
    public ModelAndView getTasks() {
        List<Task> tasks = taskService.selectTasks();
        return new ModelAndView("test/page-testtask").addObject("tasks", tasks);
    }

    @GetMapping("/task")
    @ResponseBody
    public Map<String, Object> getTask(Integer id) {
        Task task = taskService.getTaskById(id);
        return new JsonResponseMessage(ResponseMsg.SUCCESS).addAttribute("task", task).returned();
    }

    @PostMapping("/task")
    @ResponseBody
    public Map<String, Object> addTask(Task task) {
        try {
            taskService.addTask(task);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return new JsonResponseMessage(ResponseMsg.SUCCESS).returned();
    }

    @PutMapping("/task")
    @ResponseBody
    public Map<String, Object> updateTask(Task task) {
        taskService.updateTask(task);
        return new JsonResponseMessage(ResponseMsg.SUCCESS).returned();
    }

    @DeleteMapping("/task")
    @ResponseBody
    public Map<String, Object> removeTask(Integer id) {
        taskService.deleteTask(id);
        return new JsonResponseMessage(ResponseMsg.SUCCESS).returned();
    }

    @GetMapping("/task/run")
    @ResponseBody
    public Map<String, Object> runTask(Integer id) throws SchedulerException {
        taskService.runTaskNow(id);
        return new JsonResponseMessage(ResponseMsg.SUCCESS).returned();
    }

    @GetMapping("/task/stop")
    @ResponseBody
    public Map<String, Object> stopTask(Integer id) {
        taskService.stopTask(id);
        return new JsonResponseMessage(ResponseMsg.SUCCESS).returned();
    }

}
